package com.fxz.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fxz.common.dto.SysMenuDto;
import com.fxz.common.lang.Result;
import com.fxz.entity.SysMenu;
import com.fxz.entity.SysRoleMenu;
import com.fxz.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fxz
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    /**
     * 通过 Principal 获取用户信息 返回菜单信息
     * @param principal
     * @return
     */
    @GetMapping("nav")
    public Result nav(Principal principal){
        //通过Principal获取用户名 根据用户名获取用户信息
        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        //根据用户id获取权限以及用户信息
        String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());
        String[] authorityArray = StringUtils.tokenizeToStringArray(authorityInfo,",");
        //获取导航栏信息
        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();
        return Result.succ(MapUtil.builder().put("authoritys",authorityArray).put("nav",navs).map());
    }

    /**
     * 根据菜单id获取菜单信息 （拥有list权限才能访问）
     * @param id 菜单id
     * @return 菜单信息
     */
    @GetMapping("/info")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result info(Long id){

        return Result.succ(sysMenuService.getById(id));
    }

    /**
     * 返回树形菜单
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list(){
        List<SysMenu> menus = sysMenuService.tree();

        return Result.succ(menus);
    }

    /**
     * 添加菜单
     * @param
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody SysMenu sysMenu){
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return Result.succ(sysMenu);
    }

    /**
     * 更新菜单 同时更新缓存
     * @param sysMenu
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Validated @RequestBody SysMenu sysMenu){
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        //清楚所有的与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.succ(sysMenu);
    }

    @DeleteMapping("/delete")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(Long id){
         //判断菜单下是否有子菜单
        int count = sysMenuService.count(
                new LambdaQueryWrapper<SysMenu>()
                        .eq(SysMenu::getParentId, id)
        );
        if(count>0){
            return Result.fail("请先删除子菜单!");
        }
        //清楚所有的与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        sysMenuService.removeById(id);
        //删除中间关联表
        sysRoleMenuService.remove(
                new LambdaQueryWrapper<SysRoleMenu>()
                    .eq(SysRoleMenu::getMenuId,id)
        );
        return Result.succ("操作成功!");
    }

}
